﻿using Abide.Classes;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;
using System;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Threading;
using System.Windows.Forms;

namespace Abide.Forms
{
    public partial class AddOnUpdater : Form
    {
        public AddOnManifest[] Manifests
        {
            get { return manifests; }
            set { manifests = value; }
        }
        
        private int index = -1;
        private AddOnManifest[] manifests;
        private AddOnManifest manifest = null;
        private bool complete = false;

        public AddOnUpdater()
        {
            InitializeComponent();
            manifests = new AddOnManifest[0];
        }
        private void AddOnUpdater_Load(object sender, EventArgs e)
        {
            //Populate List
            addOnList.Items.Clear();
            addOnList.Items.AddRange(manifests);
            BringToFront();

            //Check
            if (manifests != null)
            {
                index = 0;
                manifest = manifests[0];
                downloadButton.Enabled = true;
            }
        }
        private void downloadButton_Click(object sender, EventArgs e)
        {
            //Disable
            downloadButton.Enabled = false;
            ControlBox = true;
            downloadProgress.Visible = true;
            downloadProgress.Style = ProgressBarStyle.Marquee;

            //Create WebClient
            WebClient client = new WebClient();
            client.DownloadFileCompleted += client_DownloadFileCompleted;

            //Loop
            string path = Path.GetTempFileName();
            client.DownloadFileAsync(new Uri(manifest.Dropbox.UpdaterUrl), path, new string[] { path, manifest.Name });

            //Wait
            ThreadPool.QueueUserWorkItem(WaitForWebClient, client);
        }
        private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            //Get data from user state...
            WebClient client = (WebClient)sender;
            string tempFile = ((string[])e.UserState)[0];
            string addOnName = ((string[])e.UserState)[1];

            //Completed properly...
            if (!e.Cancelled && e.Error == null)
            {
                ZipFile zipFile = new ZipFile(File.OpenRead(tempFile));
                byte[] buffer = null;
                foreach (ZipEntry item in zipFile)
                {
                    if (!item.IsFile)
                        continue;
                    string entryFileName = item.Name;
                    buffer = new byte[4096];
                    Stream zipStream = zipFile.GetInputStream(item);
                    string filePath = Path.Combine(Program.AddOnsPath, addOnName, entryFileName);
                    Directory.CreateDirectory(Path.GetDirectoryName(filePath));
                    using (FileStream fs = File.Create(filePath))
                        StreamUtils.Copy(zipStream, fs, buffer);
                }
            }

            //Check...
            if (index + 1 < manifests.Length)
            {
                //Increment
                index++;
                manifest = manifests[index];

                //Loop
                string path = Path.GetTempFileName();
                client.DownloadFileAsync(new Uri(manifest.Dropbox.UpdaterUrl), path, new string[] { path, manifest.Name });
            }
            else
                complete = true;
        }
        private void WaitForWebClient(object state)
        {
            //Get WebClient
            WebClient client = (WebClient)state;

            //Check
            while (!complete)
                Thread.Sleep(1);

            //Done
            Invoke(new MethodInvoker(Close));
        }
    }
}
